# -*- coding: utf-8 -*-

import os
import sys
import getopt
import time
import datetime
import shutil
import subprocess
import plistlib


# 检测必须的环境变量
def checkEnvironVariate(export):
    variate = os.environ.get(export)
    if variate == None:
        print '环境变量没有定义，请先定义它:=>  ', export
        sys.exit(0)
        pass
    return variate

# unity 路径
UNITY_PATH = checkEnvironVariate("UNITY_PATH")
GIT_VERSION = 'null'
VERSION_VALUE = '1.0.0'
CODE_VALUE = '0'
BUILDINFO_PATH = os.getcwd() + '/XcodeProj/Info.plist'
IPA_PATH = os.getcwd() + '/ipa'
BUILD_MODE = ["dev", "dist"]
BUILD_STATUS = 'Release'
TARGET_NAME = 'Unity-iPhone'
PRODUCE_NAME = 'endlessrunnerbase'

# 获取当前版本号和code值
def getBundleVersion():
    if (os.path.exists(BUILDINFO_PATH)):
        try:
            plist = plistlib.readPlist(BUILDINFO_PATH)
            VERSION_VALUE = plist["CFBundleShortVersionString"]
            CODE_VALUE = plist["CFBundleVersion"]
        except Exception as e:
            print "info.plist解析失败： " + BUILDINFO_PATH, e
        return
    else:
        print "没有找到info文件： " + BUILDINFO_PATH


# 修改当前版本号和code值
def modifyBundleVersion():
    if (os.path.exists(BUILDINFO_PATH)):
        # 用plistlib.writePlist方法必须要重新覆盖整个info.plist，这边用系统的PlistBuddy方法修改
        os.system('/usr/libexec/PlistBuddy -c "Set:CFBundleShortVersionString %s" %s' % (VERSION_VALUE, BUILDINFO_PATH))
        os.system('/usr/libexec/PlistBuddy -c "Set:CFBundleVersion %s" %s' % (CODE_VALUE, BUILDINFO_PATH))
        return


# 先获取系统值
getBundleVersion()


# 下载库工程
def downLoadSG_iosLib():
    cwd = os.getcwd()
    # 判断库工程是否存在，如果存在执行git pull，否则执行git clone
    if (os.path.exists('./lib_sg_projects/')):
        os.chdir('./lib_sg_projects/')
        os.system('git pull origin xxxxxxx')
    else:
        # 下载库工程
        os.system('git clone -b xxxxxxxxx XXXXXXXXXXXX')

    os.chdir(cwd)
    return


# 获取git哈希code
def getGitVersionHashCode():
    info = os.popen('git rev-list HEAD -n 1 | cut -c 1-7').readlines()
    for line in info:
        GIT_VERSION = line.strip('\r\n')
        break


# 导出xcode工程
def exportXcodeProj():
    os.system(
        UNITY_PATH + " -projectPath " + os.getcwd() + " -executeMethod ProjectBuild.BuildForIPhone " + VERSION_VALUE + " " + CODE_VALUE + " -quit")
    print "OK!, 导出xcode工程完成"


# 创建ipa文件夹
def makeIpaFile():
    if (os.path.exists(IPA_PATH)):
        os.system("find ./ipa -type f -name \"*.ipa\" | xargs rm -rf")
    else:
        # 创建新文件夹
        os.system("mkdir " + IPA_PATH)


# 编译库工程
def buildLibSg():
    tmp = os.getcwd()
    libPath = './lib_sg_projects/lib_common_ios/'
    if (os.path.exists(libPath)):
        os.chdir(libPath)
        os.system("xcodebuild -target SG_project_ios -configuration " + BUILD_STATUS + " -sdk iphoneos build")
    else:
        print "库工程不存在，请确认是否从git中获取成功： " + libPath
        os.system.exit(0)

    # 回到原目录
    os.chdir(tmp)


# 编译主工程
def buildTarget(certificate):
    tmp = os.getcwd()
    os.chdir('./XcodeProj')
    # os.system("xcodebuild -target " + TARGET_NAME + " -configuration " + BUILD_STATUS + " -sdk iphoneos build CODE_SIGN_IDENTITY="+certificate)
    # 字符串尽量使用下面这种方法，特殊符号比较方便处理
    cmd = 'xcodebuild -target %s -configuration %s -sdk iphoneos build CODE_SIGN_IDENTITY="%s" ' % (
    TARGET_NAME, BUILD_STATUS, certificate)
    # xcodebuild -target %s -sdk %s -configuration %s GCC_PREPROCESSOR_DEFINITIONS="%s" build' %(project, , SDK, configuration, definitions)
    os.system(cmd)
    # 回到原目录
    os.chdir(tmp)


# sign and package
def packageIpa(provisioningProfile, certificate):
    ORIIPA_PATH = os.getcwd() + '/XcodeProj/build/' + BUILD_STATUS + "-iphoneos/" + PRODUCE_NAME + ".app"
    cmd = 'xcrun -sdk iphoneos PackageApplication -v %s -o %s/UnclearRun_%s.ipa --sign "%s" --embed %s ' % (
    ORIIPA_PATH, IPA_PATH, BUILD_STATUS, certificate, provisioningProfile)
    # os.system("xcrun -sdk iphoneos PackageApplication -v "+ORIIPA_PATH+" -o "+IPA_PATH+"/test.ipa"+" --sign "+certificate+" --embed "+provisioningProfile)
    os.system(cmd)


# 根据打包模式打包
def execute_makeipa(buildmode):
    global BUILD_STATUS
    CODE_SIGN_IDENTITY = ""
    PROVISONNIING_PROFILE = ""
    if 'dev' == buildmode:
        BUILD_STATUS = 'Debug'
        PROVISONNIING_PROFILE = os.popen(
            "find " + os.getcwd() + "/mobileProvision/dev -type f -name \"*.mobileprovision\"").read()
        CODE_SIGN_IDENTITY = "iPhone Developer: xxxxxx"
    else:
        BUILD_STATUS = 'Release'
        PROVISONNIING_PROFILE = os.popen(
            "find " + os.getcwd() + "/mobileProvision/dist -type f -name \"*.mobileprovision\"").read()
        CODE_SIGN_IDENTITY = "iPhone Distribution: xxxxxxxx"

    # 编译库工程
    buildLibSg()
    # 编译主工程
    buildTarget(CODE_SIGN_IDENTITY)
    # 打包主工程
    packageIpa(PROVISONNIING_PROFILE, CODE_SIGN_IDENTITY)


# 生成ipa
def makeIPA():
    # 下载库工程
    downLoadSG_iosLib()
    # 修改配置文件
    modifyBundleVersion()
    # 创建包文件
    makeIpaFile()

    for bm in BUILD_MODE:
        execute_makeipa(bm)
    return


# usage
def usage():
    print 'ipa_Builder.py usage:'
    print '-h, --help:    帮助信息.'
    print '-v, --version: 打包的版本号，不输入默认按照Unity PlayerSetting中设置并打包'
    print '-c, --code:    打包ipa的build值，Unity PlayerSetting中设置并打包'


# -------------- main --------------
if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], "hv:c:")
    for op, value in opts:
        if op == "-v":
            VERSION_VALUE = value
        elif op == "-c":
            CODE_VALUE = value
        elif op == "-h":
            usage()
            sys.exit()

    # 打包
    exportXcodeProj()
    makeIPA()
